<template>
  <el-dialog
    v-model="isShow"
    :title="isNew ? '新建文章' : '编辑文章'"
    width="50%"
    :before-close="handleClose"
  >
    <el-form ref="formRef" :model="form" label-width="100px">
      <el-form-item label="文章标题" prop="title" required>
        <el-input v-model="form.title" placeholder="请输入文章标题" />
      </el-form-item>

      <el-form-item label="专题" prop="topic">
        <el-select v-model="form.topic" placeholder="请选择专题">
          <el-option
            v-for="topic in topics"
            :key="topic.id"
            :label="topic.name"
            :value="topic.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="时间范围" required>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option
            v-for="status in statusOptions"
            :key="status.value"
            :label="status.label"
            :value="status.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="进度" prop="progress">
        <el-slider v-model="form.progress" :step="5" show-input />
      </el-form-item>

      <el-form-item label="内容摘要" prop="summary">
        <el-input v-model="form.summary" type="textarea" :rows="4" placeholder="请输入文章摘要" />
        <el-upload
          class="upload-demo"
          :show-file-list="false"
          :before-upload="handleMarkdownUpload"
          accept=".md"
        >
          <el-button type="primary">导入Markdown文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useGanttStore } from '@/store/modules/ganttStore';
import type { BlogPost } from '@/components/GanttChart/types';

const props = defineProps({
  post: {
    type: Object as () => BlogPost | null,
    default: null
  },
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['save', 'close']);

const isShow = ref(props.visible);
const formRef = ref();
const dateRange = ref<[string, string] | []>([]);
const form = ref({
  id: '',
  title: '',
  topic: '',
  status: 'draft',
  progress: 0,
  summary: ''
});

const ganttStore = useGanttStore();
const topics = computed(() => ganttStore.topics);

const statusOptions = [
  {
    value: 'draft',
    label: '草稿'
  },
  {
    value: 'writing',
    label: '写作中'
  },
  {
    value: 'review',
    label: '审核中'
  },
  {
    value: 'scheduled',
    label: '待发布'
  },
  {
    value: 'published',
    label: '已发布'
  },
  {
    value: 'archived',
    label: '已归档'
  }
];

const resetForm = () => {
  form.value = {
    id: '',
    title: '',
    topic: topics.value[0]?.id || '',
    status: 'draft',
    progress: 0,
    summary: ''
  };

  const today = new Date();
  const endDate = new Date();
  endDate.setDate(today.getDate() + 3);

  dateRange.value = [today.toISOString().split('T')[0], endDate.toISOString().split('T')[0]];
};

const isNew = computed(() => !props.post?.id);

watch(
  () => props.post,
  newPost => {
    if (newPost) {
      form.value = {
        id: newPost.id,
        title: newPost.title,
        topic: newPost.topic,
        status: newPost.status,
        progress: newPost.progress * 100,
        summary: newPost.summary || ''
      };

      dateRange.value = [newPost.startDate, newPost.endDate];
    } else {
      resetForm();
    }
  },
  { immediate: true }
);

const handleClose = () => {
  emit('close');
};

const handleMarkdownUpload = file => {
  const reader = new FileReader();
  reader.onload = e => {
    form.value.content = e.target.result;
  };
  reader.readAsText(file);
  return false;
};

const handleSave = async () => {
  const isValid = await formRef.value.validate();
  if (!isValid) return;
  const postData = {
    ...form.value,
    progress: form.value.progress / 100,
    startDate: dateRange.value[0],
    endDate: dateRange.value[1],
    startTime: dateRange.value[0] && ganttStore.gstc?.api.time.date(dateRange.value[0]).valueOf(),
    endTime: dateRange.value[1] && ganttStore.gstc?.api.time.date(dateRange.value[1]).valueOf()
  };

  console.log('post editor form', postData);
  emit('save', postData);
  emit('close');
};
</script>
